import { authorizedList } from '@/api/authorized';
import {
  productShopifyAdd,
  productShopifyEdit,
  productCategoryList,
  productCategoryAdd,
  productTagList,
  productTagAdd,
  vendorList,
  vendorAdd,
  productVariantList,
  productShopifyRead
} from '@/api/product';
import UE from '@/components/Ueditor/ueditor.vue';
import AllTag from '../components/allTag';
import SingleCategory from '../components/singleCategory';
import AllVendor from '../components/allVendor';
import AllVariant from '../components/allVariant';
import ThumbnailDialog from '../components/thumbnailDialog';
import UploadVariant from '../components/uploadVariantShopify';
import BatchModify from '../components/batchModify';
import ProviewImg from '@/components/Proview/proviewImg';
import {
  shopifyRules,
  watchSpecifications,
  toggleCheck,
  changeVariantSku
} from './commonDet';
export default {
  components: {
    UE,
    ThumbnailDialog,
    AllTag,
    SingleCategory,
    AllVendor,
    UploadVariant,
    BatchModify,
    AllVariant,
    ProviewImg
  },
  data() {
    return {
      pageType: 'Add',
      storeId: '', // 店铺ID
      productId: null, // 商品ID
      storeList: [],
      categoryOptions: [], // 分类列表
      tagOptions: [],
      vendorOptions: [],
      formData: {
        taxStatus: 0,
        isManageInventory: 0,
        allowBackorders: 0,
        isVirtual: 0,
        productTagIds: [],
        productCategoryIds: null,
        type: 0,
        // 生成的变种信息
        specificationData: []
      },
      content: {},
      rules: shopifyRules(this.checkStr, this),
      loading: true,
      ue: 'ue',
      thumbnailShow: false,
      images: [],
      proviewUrl: '', // 预览图片Url
      timeChange: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 选择时间范围
        }
      },
      viewTags: false,
      viewCategory: false,
      viewVendor: false,
      viewVariant: false,
      chargeTax: '',
      allListLeaf: [], // 所有规格叶子节点，比对规格ID使用
      specifications: [
        // 规格信息(树结构)
        {
          parent: '',
          son: []
        }
      ],
      firstRandom: true, // 首次渲染变种信息
      cloneSpecificationData: [], // 商品中保存的规格信息，新加规格信息若在其中存在，使用其数据
      specList: [],
      selectOptions: [], // 当前选取规格值得子选项
      variantIndex: 0,
      selectedId: null,
      variantDialogVisible: false,
      batchVisible: false,
      writeLabel: '' // 批量写入变种信息的具体参数
    };
  },
  watch: {
    specifications: {
      // 监听规格信息变化，生成变种信息
      handler(newVal, oldValue) {
        watchSpecifications(newVal, this, 'shopify');
      },
      deep: true
    }
  },
  mounted() {
    this.$set(this.formData, 'rules', this.rules);
    if (this.$route.params.storeId === undefined) {
      // 添加
      if (this.$route.params.productId === undefined) {
        this.pageType = 'Add';
        this.getStoreList(true);
        this.loading = false;
      } else {
        this.productId = Number(this.$route.params.productId);
        this.pageType = 'Edit';
        this.getStoreList(true, true);
      }
    } else {
      this.storeId = Number(this.$route.params.storeId);
      this.productId = Number(this.$route.params.productId);
      this.pageType = 'Edit';
      this.getStoreList(false, true);
    }
  },
  methods: {
    async getStoreList(str, otherData) {
      // 获取店铺列表
      const res = await authorizedList({
        storeType: 'SHOPIFY'
      });
      this.storeList = res.data;
      if (str && res.data.length > 0) {
        this.storeId = res.data[0].id;
        if (otherData) {
          this.vendorList(true);
          this.productCategoryList(true);
          this.productTagList(true);
          this.chosedStore(this.storeId);
        }
      } else if (!str && otherData) {
        this.vendorList(true);
        this.productCategoryList(true);
        this.productTagList(true);
        this.chosedStore(this.storeId);
      }
    },
    chosedStore(storeId) {
      productVariantList({ storeId }).then((res) => {
        // 规格
        var arr = [];
        res.data.forEach((ele, i) => {
          arr[i] = ele.name;
          arr[i]['value'] = ele.name.name;
          arr[i]['listLeaf'] = ele.values;
        });
        this.specList = arr;
        var allListLeaf = [];
        this.specList.forEach((item) => {
          allListLeaf = allListLeaf.concat(item.listLeaf);
        });
        this.allListLeaf = allListLeaf;
        if (this.productId) {
          this.productRead();
        }
      });
    },
    productRead() {
      productShopifyRead(this.productId).then((res) => {
        const data = JSON.parse(JSON.stringify(res.data));
        // 价格/100
        if (data.product.type === 1) {
          data.inventories.forEach((item) => {
            item.salePrice /= 100;
            item.regularPrice /= 100;
          });
        }
        data.product.regularPrice /= 100;
        data.product.salePrice /= 100;
        this.formData = data.product;
        this.$set(
          this.formData,
          'productCategoryIds',
          Number(data.product.categoryIds)
        );
        this.$set(
          this.formData,
          'productTagIds',
          data.product.tagIds === ''
            ? []
            : data.product.tagIds.split(',').map((item) => Number(item))
        );
        if (this.formData.vendorId === 0) {
          delete this.formData.vendorId;
        }
        this.$set(this.formData, 'specificationData', data.inventories);
        this.content = data.content || {};
        this.images = data.images || [];
        this.$set(this.formData, 'rules', this.rules);
        if (data.product.type === 1) {
          this.cloneSpecificationData = JSON.parse(
            JSON.stringify(data.inventories)
          );
          var idStr = '';
          data.inventories.forEach((item, index) => {
            idStr += item.titleIds + ',';
          });
          // 解析转换 规格信息 数据
          var newArr = [];
          data.variants.forEach((item) => {
            var obj = {};
            obj['parent'] = item.name;
            obj['son'] = [];
            var objSon = [];
            var children = this.specList.find((ele) => ele.id === item.id)
              .listLeaf;
            for (var a = 0; a < children.length; a++) {
              if (idStr.split(',').includes(String(children[a].id))) {
                objSon.push(children[a].name);
              }
            }
            obj['son'] = objSon;
            newArr.push(obj);
          });
          this.specifications = newArr;
        } else if (data.product.type === 0) {
          this.formData['productVariantIds'] = [];
        }
        this.loading = false;
      });
    },
    resetVariantList(val) {
      if (!val) return;
      productVariantList({ storeId: this.storeId }).then((res) => {
        // 规格
        var arr = [];
        res.data.forEach((ele, i) => {
          arr[i] = ele.name;
          arr[i]['value'] = ele.name.name;
          arr[i]['listLeaf'] = ele.values;
        });
        this.specList = arr;
        var allListLeaf = [];
        this.specList.forEach((item) => {
          allListLeaf = allListLeaf.concat(item.listLeaf);
        });
        this.allListLeaf = allListLeaf;
      });
    },
    variantNameChange(i) {
      this.specifications[i].son = [];
    },
    productCategoryList(val) {
      // 获取分类
      if (val) {
        productCategoryList({ storeId: this.storeId, parentId: 0 }).then(
          (res) => {
            this.categoryOptions = res.data;
          }
        );
      }
    },
    categoryChange(val) {
      // 添加分类
      if (typeof val === 'string') {
        const params = {
          isLeaf: 0,
          parentId: 0,
          name: val,
          storeId: this.storeId
        };
        productCategoryAdd(params).then((res) => {
          if (res.code === 200) {
            this.productCategoryList(true);
          } else {
            this.formData.productCategoryIds = '';
          }
        });
      }
    },
    productTagList(val) {
      // 标签列表
      if (val) {
        productTagList(this.storeId).then((res) => {
          this.tagOptions = res.data;
        });
      }
    },
    productTagAdd(val) {
      // 添加标签
      const value = val[val.length - 1];
      if (typeof value === 'string') {
        const params = {
          isLeaf: 0,
          parentId: 0,
          name: value,
          storeId: this.storeId
        };
        productTagAdd(params).then((res) => {
          if (res.code === 200) {
            productTagList(this.storeId).then((res) => {
              if (res.code === 200) {
                this.tagOptions = res.data;
                const id = res.data.filter((item) => item.name === value)[0].id;
                this.formData.productTagIds[
                  this.formData.productTagIds.length - 1
                ] = id;
              }
            });
          } else {
            this.formData.productTagIds.splice(val.length - 1, 1);
          }
        });
      }
    },
    getClick(e, str) {
      if (e.target.tagName === 'SPAN' && e.target.className === '') {
        switch (str) {
          case 'vendor':
            this.viewVendor = true;
            break;
          case 'tag':
            this.viewTags = true;
            break;
          case 'category':
            this.viewCategory = true;
            break;
        }
      }
    },
    vendorList(val) {
      if (val) {
        vendorList().then((res) => {
          this.vendorOptions = res.data;
        });
      }
    },
    vendorAdd(val) {
      // 添加标签
      if (typeof val === 'string') {
        const params = {
          name: val,
          storeId: this.storeId
        };
        vendorAdd(params).then((res) => {
          if (res.code !== 200) {
            this.formData.vendorId = '';
          } else {
            this.vendorList(true);
          }
        });
      }
    },
    goToVariant() {
      if (!this.storeId) {
        this.$message.warning('Please choose a store first');
        return;
      }
      const route = this.$router.resolve({
        name: 'Variants',
        params: {
          storeId: this.storeId
        }
      });
      window.open(route.href, '_blank');
    },
    productShopifyAdd(params) {
      // 添加商品
      productShopifyAdd(params).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$router.go(-1);
        }
      });
    },
    productShopifyEdit(params) {
      productShopifyEdit(params).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$router.go(-1);
        }
      });
    },
    submitData() {
      this.$refs['productForm'].validate((valid) => {
        if (valid) {
          // 校验商品缩略图
          if (this.images.length === 0) {
            const offsetTop = document.getElementById('Images').offsetTop;
            document.documentElement.scrollTop = offsetTop - 90;
            this.$message.warning('Please Add/Select the images');
            return;
          }
          const params = JSON.parse(JSON.stringify(this.formData));
          this.content['description'] = this.$refs.ue.getUEContent();
          params.content = this.content;
          // 校验商品描述
          if (params.content['description'] === '') {
            const offsetTop = document.getElementById('Description').offsetTop;
            document.documentElement.scrollTop = offsetTop - 90;
            this.$message.warning('Please fill in the description');
            return;
          }
          params['storeId'] = this.storeId;
          params['inventories'] = JSON.parse(
            JSON.stringify(this.formData.specificationData)
          );
          params['productImageIds'] = this.images.map((item) => item.id);
          if (typeof params.vendorId === 'string') {
            // 提交数据时供应商为新加的时，匹配下对应id
            params.vendorId = this.vendorOptions.filter(
              (item) => item.name === params.vendorId
            )[0].id;
          }
          if (typeof params.productCategoryIds === 'string') {
            // 提交数据时分类为新加的时，匹配下对应id
            params.productCategoryIds = this.categoryOptions.filter(
              (item) => item.name === params.productCategoryIds
            )[0].id;
          }
          const id = [params['productCategoryIds']];
          params['productCategoryIds'] = id;
          // 价格*100
          if (params.type === 1) {
            if (params.inventories.length === 0) {
              return this.$message.warning('Please add variant information');
            }
            let haveEmpty = false;
            params.inventories.forEach((item) => {
              if (item.thumbnailUri === '') {
                haveEmpty = true;
                return;
              }
              item.salePrice = Math.round(item.salePrice * 100);
              item.regularPrice = Math.round(item.regularPrice * 100);
              item.quantity *= 1;
            });
            if (haveEmpty) {
              return this.$message.warning(
                'Please upload pictures of variations'
              );
            }
          } else if (params.type === 0) {
            params.inventories = [];
            params.productVariantIds = [];
          }
          params.regularPrice = Math.round(params.regularPrice * 100);
          params.salePrice = Math.round(params.salePrice * 100);
          params.inventoryQuantity = params.inventoryQuantity * 1 || 0;
          if (this.pageType === 'Add') {
            params['inventoryStatus'] = 0;
            this.productShopifyAdd(params);
          } else if (this.pageType === 'Edit') {
            params.productGroupIds = [];
            this.productShopifyEdit(params);
          }
        } else {
          this.$message.warning('Please complete the information');
          return false;
        }
      });
    },
    changeVariantSku(val) {
      changeVariantSku(val, this);
    },
    toggleCheck(val, label) {
      // 取消勾选表单复选框，清空对应数据
      toggleCheck(val, label, this);
    },
    specToggleCheck(val, label, index) {
      // 取消勾选变种内表单复选框，清空对应数据
      if (val === 0) {
        if (label === 'isManage') {
          this.formData.specificationData[index]['quantity'] = 0;
        }
      } else {
        if (label === 'isVirtual') {
          this.formData.specificationData[index]['weight'] = '0';
        }
      }
    },
    getSelectedTag(data) {
      this.viewTags = false;
      this.formData.productTagIds = data;
    },
    getSelectedCategory(data) {
      this.viewCategory = false;
      this.formData.productCategoryIds = data;
    },
    closeCategoryDialog(data) {
      if (!data) {
        this.formData.productCategoryIds = '';
      }
      this.viewCategory = false;
    },
    getSelectedVendor(data) {
      this.viewVendor = false;
      this.$set(this.formData, 'vendorId', data);
    },
    closeVendorDialog(data) {
      if (!data) {
        this.formData.vendorId = '';
      }
      this.viewVendor = false;
    },
    choseThumbnail(data) {
      // 关闭图片缩略图弹窗
      this.thumbnailShow = false;
      if (data && data.constructor === Array) {
        this.images = data;
        const imageIds = data.map((item) => item.id);
        this.formData.specificationData.forEach((item, index) => {
          if (!imageIds.includes(item.imageId)) {
            this.$set(this.formData.specificationData[index], 'imageId', 0);
            this.$set(
              this.formData.specificationData[index],
              'thumbnailUri',
              ''
            );
          }
        });
      }
    },
    showVariantDialog(index, id) {
      this.variantIndex = index;
      this.selectedId = id;
      this.variantDialogVisible = true;
    },
    setVariantImg(obj) {
      if (obj.id !== undefined && obj.id !== this.selectedId) {
        this.formData.specificationData[this.variantIndex].thumbnailUri =
          obj.uri;
        this.formData.specificationData[this.variantIndex].imageId = obj.id;
      }
      this.variantDialogVisible = false;
    },
    removeItem(index) {
      this.specifications.splice(index, 1);
    },
    closeBatch(data) {
      this.batchVisible = false;
      if (data) {
        this.formData.specificationData.forEach((item) => {
          this.$set(item, this.writeLabel, data);
        });
      }
    },
    setPrice(label) {
      // 批量设置变种信息
      if (this.formData.specificationData.length === 0) {
        return this.$message.warning('Please add the variant first');
      }
      this.writeLabel = label;
      this.batchVisible = true;
    },
    batchCheckChange(val, label) {
      // 批量设置变种信息内复选框
      this.formData.specificationData.forEach((item) => {
        item[label] = val;
        if (label === 'isVirtual' && val === 1) {
          item['weight'] = '0';
        } else if (label === 'isManage' && val === 0) {
          item['quantity'] = 0;
        }
      });
    },
    deleteSkuItem({ row, $index }) {
      // 删除变种信息
      this.formData.specificationData.splice($index, 1);
    },
    addSpecificationItem() {
      // 添加规格信息
      this.specifications.push({
        parent: '',
        son: []
      });
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    goBack() {
      this.$router.go(-1);
    }
  }
};
